import { typeConstants } from '../config'
import * as actionTypes from './actionTypes'
import { v4 as uuidv4 } from 'uuid'
export default {
  namespaced: true,
  state: {
    // 画布数据
    layouts: {
      scale: 1, // 缩放比
      width: 960, // 宽度
      height: 540, // 高度
      background: { // 背景
        id: uuidv4(), // 唯一id
        type: typeConstants.BACKGROUND, // 类型
        color: '#f8f8f8', // 背景色
        image: null
      },
      elements: [] // 主要元素标签(图片, 文字)
    },
    current: null, // 当前选中模块
    currentIndex: null,
    currentEditor: null, // 当前选中文本编辑器
    batchPreview: null // 批量预览列表
  },
  actions: {
    // 设置更新视图数据
    setData ({ commit, state }, data) {
      return new Promise((resolve, reject) => {
        commit(actionTypes.SET_DATA, data)
        resolve()
      })
    },
    // 设置图层数据
    setElement ({ commit, state }, payload) {
      return new Promise((resolve, reject) => {
        commit(actionTypes.SET_ELEMENT, payload)
        resolve({
          length: state.layouts.elements.length
        })
      })
    },
    // 设置当前选中模块, current是图层数据
    setCurrent ({ commit, state }, layer) {
      return new Promise((resolve, reject) => {
        commit(actionTypes.SET_CURRENT, layer)
        resolve()
      })
    },
    // 设置当前选中模块的序号
    setCurrentIndex ({ commit, state, }, index) {
      return new Promise((resolve, reject) => {
        commit(actionTypes.SET_CURRENT_INDEX, index)
        resolve()
      })
    },
    // 设置当前元素的编辑器
    setCurrentEditor ({ commit, state }, editor) {
      return new Promise((resolve, reject) => {
        commit(actionTypes.SET_CURRENT_EDITOR, editor)
        resolve()
      })
    }
  },
  mutations: {
    [actionTypes.SET_DATA] (state, layouts) {
      state.layouts = {
        ...state.layouts,
        ...layouts
      }
    },
    [actionTypes.SET_ELEMENT] (state, { type, value, index }) {
      switch (type) {
        case 'push': // 新增
          state.layouts.elements.push(value)
          break;
        case 'delete': // 删除
          state.layouts.elements.splice(index, 1)
          break
        default: // 更新
          state.layouts.elements.splice(index, 1, value)
          break;
      }
    },
    [actionTypes.SET_CURRENT] (state, layer) {
      state.current = layer
    },
    [actionTypes.SET_CURRENT_INDEX] (state, index) {
      state.currentIndex = index
    },
    [actionTypes.SET_CURRENT_EDITOR] (state, editor) {
      state.currentEditor = editor
    }
  }
}